#include "reactor/event_loop_thread.hpp"
#include "reactor/event_loop.hpp"

namespace reactor {

EventLoopThread::EventLoopThread()
    : _loop(nullptr) {}

EventLoopThread::~EventLoopThread() {
    if (_loop) {
        _loop->quit();
        if (_thread.joinable()) {
            _thread.join();
        }
    }
}

EventLoop* EventLoopThread::startLoop() {
    _thread = std::thread(&EventLoopThread::threadFunc, this);
    EventLoop* loop = nullptr;
    {
        std::unique_lock<std::mutex> lock(_mutex);
        while (_loop == nullptr) {
            _cond.wait(lock);
        }
        loop = _loop;
    }
    return loop;
}

void EventLoopThread::threadFunc() {
    EventLoop loop;
    {
        std::lock_guard<std::mutex> lock(_mutex);
        _loop = &loop;
        _cond.notify_one();
    }
    loop.loop();
    std::lock_guard<std::mutex> lock(_mutex);
    _loop = nullptr;
}

} // namespace reactor
